package com.example;

import org.junit.Test;

import java.lang.reflect.Constructor;

public class ReflectionConstructorDemo {

    @Test
    public void test1() throws ClassNotFoundException {
        Class<?> clazz = Class.forName("com.example.Person");
        System.out.println(clazz.getName());
        System.out.println(clazz.getCanonicalName());
        System.out.println(clazz.getSimpleName());
        System.out.println(clazz.getTypeName());
    }

    // 获取Class的四种方式
    @Test
    public void test2() throws ClassNotFoundException {
        Class<?> clazz = Class.forName("com.example.Person");
        System.out.println(clazz.getName());

        Class<Person> personClass = Person.class;
        System.out.println(personClass.getName());
        System.out.println(int.class.getName());
        System.out.println(String[].class.getName());

        Person person = new Person();
        Class<? extends Person> personAnotherClass = person.getClass();
        System.out.println(personAnotherClass.getName());

        Class<Long> longClass = Long.TYPE;
        System.out.println(longClass.getName());
    }

    // 反射：public Person()
    @Test
    public void test3() throws Exception {
        Class<?> clazz = Class.forName("com.example.Person");
        Constructor<?> constructor = clazz.getConstructor(null);
        Object object = constructor.newInstance(null);
        System.out.println(object);
    }

    // 反射：public Person(String name)
    @Test
    public void test4() throws Exception {
        Class<?> clazz = Class.forName("com.example.Person");
        Constructor<?> constructor = clazz.getConstructor(String.class);
        Object object = constructor.newInstance("jack");
        System.out.println(object);
    }

    // 反射：public Person(String name, int age)
    @Test
    public void test5() throws Exception {
        Class<?> clazz = Class.forName("com.example.Person");
        Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
        Object object = constructor.newInstance("jack", 30);
        System.out.println(object);
    }

    // 反射：private Person(int age)
    @Test
    public void test6() throws Exception {
        Class<?> clazz = Class.forName("com.example.Person");
        Constructor<?> constructor = clazz.getDeclaredConstructor(int.class);
        constructor.setAccessible(true);
        Object object = constructor.newInstance(100);
        System.out.println(object);
    }

    @Test
    public void test7() throws Exception {
        Class<?> clazz = Class.forName("com.example.Person");
        Constructor[] constructors = clazz.getDeclaredConstructors();
        System.out.println(constructors.length);
    }

}
